package net.tensor.skynet.adapter

import android.content.Intent
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.annotation.RequiresApi
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import net.tensor.skynet.R
import net.tensor.skynet.actity.ItemDetailActivity
import net.tensor.skynet.common.user.entity.User
import net.tensor.skynet.entity.DataContainer
import net.tensor.skynet.fragment.ItemDetailFragment
import net.tensor.skynet.fragment.ListDemoFragment

@RequiresApi(Build.VERSION_CODES.M)
class CardAdapter : RecyclerView.Adapter<ViewHolder>() {
    private var onClickListener: View.OnClickListener

    init {
        onClickListener = View.OnClickListener { v ->
            val item = v.tag as User
            val intent = Intent(v.context, ItemDetailActivity::class.java).apply {
                putExtra(ListDemoFragment.ARG_ITEM_ID, item.id)
                putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id)
            }
            v.context.startActivity(intent)
        }
    }

    override fun getItemCount(): Int {
        return DataContainer.USER_ITEMS.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(parent.inflate(R.layout.row_empty_card))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = DataContainer.USER_ITEMS[position]
        holder.itemId.text = item.id
        holder.itemName.text = item.name
        with(holder.itemCard) {
            tag = item
            setOnClickListener(onClickListener)
        }
    }

    override fun getItemViewType(position: Int) = if (position == 0) 0 else 1
}

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val itemId: TextView = itemView.findViewById(R.id.item_id)
    val itemName: TextView = itemView.findViewById(R.id.item_name)
    val itemCard: CardView = itemView.findViewById(R.id.itemCard)
}

private fun ViewGroup.inflate(@LayoutRes layout: Int, attach: Boolean = false) =
    LayoutInflater.from(context).inflate(layout, this, attach)



